package nina.yiyou.salary.input.info

import luj.groovy.excel.api.LugExcel
import luj.groovy.excel.api.table.Table
import luj.groovy.excel.api.table.body.Row
import luj.groovy.excel.api.table.header.Header
import luj.groovy.excel.api.table.header.HeaderField
import nina.yiyou.salary.input.util.ExcelReadOpener
import nina.yiyou.salary.input.util.IdMapMaker
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.Workbook

import java.util.stream.Collectors

/**
 * 读取公积金表
 */
class FundExcelV2Reader {

  FundExcelV2Reader(String excelPath, Map<String, Map> basicMap) {
    _excelPath = excelPath
    _basicMap = basicMap
  }

  Map read() {
    Workbook workbook = new ExcelReadOpener(_excelPath).openXls()
    List<Map> lines = readLines(workbook.getSheetAt(0))
    workbook.close()

    String accountKey = COLUMN_LIST[1][1]
    def getId = { Map line ->
      def account = line[accountKey] as String
      return account[0..<-2]
    }

    Map idMap = new IdMapMaker(_basicMap).make()
    return lines.findAll { it[accountKey] }
        .collect { [it, getId(it)] }
        .findAll { idMap.containsKey(it[1]) }
        .collectEntries { [idMap[it[1]], it[0]] }
  }

  private List<Map> readLines(Sheet sheet) {
    Table table = LugExcel.table(sheet).header {
      startCell('A3')
      rowSize(1)
    }.build()

    return table.body.rows.stream()
        .map { toLineMap(it, table.header) }
        .collect(Collectors.toList())
  }

  private Map toLineMap(Row row, Header header) {
    def toEntry = { String path, String resultKey ->
      HeaderField field = header.getField(path)
      return [resultKey, row.getFieldValue(field)]
    }
    return COLUMN_LIST.collectEntries(toEntry)
  }

  private static final List COLUMN_LIST = [
      ['个人姓名', '姓名'],
      ['公积金账号', '账号'],
      ['个人发生额', '个人'],
  ]

  private final String _excelPath
  private final Map<String, Map> _basicMap
}
